/**
 * 
 */
package com.hanhai.zrb.api.facade.impl;

import java.io.IOException;
import javax.annotation.Resource;
import javax.jws.WebService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.hanhai.zrb.api.biz.result.UserCenterResult;
import com.hanhai.zrb.api.biz.service.MessageSendService;
import com.hanhai.zrb.api.biz.service.SMSCodeService;
import com.hanhai.zrb.api.biz.service.UserRegisterCheckService;
import com.hanhai.zrb.api.biz.service.UserRegisterService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.biz.service.ValidateCodeSendService;
import com.hanhai.zrb.api.client.facade.RegisterFacade;
import com.hanhai.zrb.api.client.result.RegisterResult;
import com.hanhai.zrb.model.common.ValidateCodeSend.BizTypeEnum;
import com.hanhai.zrb.model.common.ValidateCodeSend.SendSMSTypeEnum;
import com.hanhai.zrb.model.user.vo.UserRegisterVo;

/**
 * @author ricky
 *
 */
@WebService(endpointInterface = "com.hanhai.zrb.api.client.facade.RegisterFacade", serviceName = "RegisterFacade")
@Service("registerFacade")
public class RegisterFacadeImpl implements RegisterFacade {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private MessageSendService messageSendService;
	@Resource
	private UserService userService;
	@Resource
	private UserRegisterService userRegisterService;
	@Resource
	private UserRegisterCheckService userRegisterCheckService;
	@Resource
	private ValidateCodeSendService validateCodeSendService;
	
	@Resource
	private SMSCodeService sMSCodeService;
	
	
	private static String regpw = "^[^\\s]{6,16}$";
	
	private static String regMobile = "^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$";
	
	/*public RegisterFacade() {
		userService  = (UserService)SpringContextUtil.getBean("userService");
		userRegisterService = (UserRegisterService)SpringContextUtil.getBean("userService");
		userRegisterCheckService = (UserRegisterCheckService)SpringContextUtil.getBean("userService");
		validateCodeSendService = (ValidateCodeSendService)SpringContextUtil.getBean("validateCodeSendService");
	}*/
	
	/**
	 * 单独校验手机号是否可以使用
	 * 如果可以使用 result=true
	 * 不能使用，result=false ，并且msg有错误信息
	 * 
	 * @param mobile
	 * @return
	 */
	public RegisterResult checkMobile(String mobile){
		RegisterResult result = new RegisterResult();
		UserCenterResult userCenterResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
		result.setSuccess(userCenterResult.isSuccess());
		result.setResultCode(userCenterResult.getResultCode());
		result.setMsg(userCenterResult.getMsg());
		return result;
	}
	
	
	/**
	 * 发送手机注册短信校验码
	 * 1、检查手机号是否可以注册
	 * 2、生成校验码并发送短信
	 * 
	 * @param mobile
	 * @return
	 */
	public RegisterResult sendMobileRegisterCode(String mobile){
		RegisterResult result = new RegisterResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				BizTypeEnum type  = BizTypeEnum.SmsBindRegister;
				int codeType = SendSMSTypeEnum.REGISTER.getIndex();
				UserCenterResult sendResult = userRegisterService.sendSMSCode(mobile, type.name(), type, codeType);
				if( sendResult.isSuccess()){
					result.setSuccess(true);
					result.setMsg("短信发送成功");
					return result;
				}
				result.setMsg(sendResult.getMsg());
			}else{
				result.setMsg("手机号码格式不正确！");
			}
		}else{
			result.setMsg("手机号码不能为空");
		}
		
		return result;
	}
	
	private String getMoblieRegisterExtraCodeIdentity(String mobile){
		return "Mobile_Register_Extral_Web_"+mobile;
	}
	/**
	 * 校验注册短信
	 * 短信验证码验证成功会返回一个extralCode 这个code是后面注册请求有效性的一个前置，避免恶意攻击注册请求
	 * 客户端收到这个code后需要缓存
	 * 
	 * @param mobile
	 * @param smsCode
	 * @return
	 */
	public RegisterResult checkMobileRegisterCode(String mobile,String smsCode){
		RegisterResult result = new RegisterResult();
		if( StringUtils.isNotBlank(mobile)){
			if(StringUtils.isNotBlank(smsCode)){
				BizTypeEnum type  = BizTypeEnum.SmsBindRegister;
				UserCenterResult checkResult = userRegisterService.checkSMSCode(mobile, smsCode, type);
				
				if( checkResult.isSuccess()){
					String identity = this.getMoblieRegisterExtraCodeIdentity(mobile);
					String extralCode = this.validateCodeSendService.createExtralCacheCode(identity);
					result.setSuccess(true);
					result.setExtralCode(extralCode);
					result.setMsg("验证成功");
					return result;
				}else{
					result.setMsg(checkResult.getMsg());
				}
			}else{
				result.setMsg("验证码不能为空");
			}
		}else{
			result.setMsg("手机号码不能为空");
		}
		
		return result;
	}
	
	/**
	 * 快速注册，会帮助用户生随机密码和随机用户名
	 * 
	 * @param mobile
	 * @param extalCode
	 * @param userType 1是企业2是政府
	 * @return
	 */
	public RegisterResult saveUserForQuickRegiester(String mobile,String extalCode,Integer userType){
		RegisterResult result = new RegisterResult();
		if(StringUtils.isBlank(mobile)){
			result.setMsg("手机号码不能为空");
			return result;
		}
		if(!mobile.matches(regMobile)){
			result.setMsg("手机号码格式不正确！");
			return result;
		}
		
		String identity = getMoblieRegisterExtraCodeIdentity(mobile);
		boolean checkResult = this.validateCodeSendService.checkExtralCacheCode(identity, extalCode);
		
		if(!checkResult){
			result.setMsg("验证码过期");
			return result;
		}
		
		UserCenterResult checkMobileResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
		if(!checkMobileResult.isSuccess()){
			result.setMsg(checkMobileResult.getMsg());
			return result;
		}
		UserRegisterVo registervo = new UserRegisterVo();
		String randomUname = createRandomUname();
		String randomPassword = creatRandomPawd();
		registervo.setUname(randomUname);
		registervo.setPassword(randomPassword);
		registervo.setUmobile(mobile);
		registervo.setUserType(userType);
		UserCenterResult registerResult = userRegisterService.doRegisterByMobile(registervo);
		if(!registerResult.isSuccess()){
			result.setMsg(checkMobileResult.getMsg());
			return result;
		}
		
		try {
			logger.info("send regiester succese sms mobile="+mobile+",passwrod="+randomPassword);
			sMSCodeService.sendSms(mobile, "注册成功，登陆密码是："+randomPassword);
			logger.info("send regiester succese sms mobile="+mobile+" succese");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			logger.error("",e);
			result.setMsg(e.getMessage());
			return result;
		}
//        try {
//			User  user = userService.findByPhone(mobile);
//			   if(null!=user){
//					List<Long> receiverUids = new ArrayList<Long>();
//					receiverUids.add(user.getUid());
//					String content = null;
//					MessageBizType bizType = MessageBizType.user_regiester_succes;
//					boolean results = messageSendService.createNotifyMessage(receiverUids, content, bizType, "");	
//			   }
//		} catch (Exception e) {
//		}
		
		result.setSuccess(true);
		result.setMsg("注册成功");
		
		/*
		 * 暂时不在登录接口中返回换新账号信息
		User user = userService.findByPhone(mobile);
		
		UserCenterResult huaxinImRegiesterResult = userRegisterService.registerHuanxinImByUid(user.getUid());
		if(huaxinImRegiesterResult.isSuccess()){
			result.setHuanxinImUsername(huaxinImRegiesterResult.getHuanxinImUserName());
			result.setHuanxinImPassword(huaxinImRegiesterResult.getHuanxinImPassword());
		}*/
		return result;
	}
	
	
	public String createRandomUname(){
		String temp = null; 
		boolean nameCanUse = false;
		while(nameCanUse==false){
			temp = RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz");
			nameCanUse = userRegisterCheckService.checkUserNameExist(temp);
		}
		return temp;
	}
	
	public String creatRandomPawd(){
		return "123456";
		//短信网关有些文案发不出去，先写死密码是123456，方便测试
		//return RandomStringUtils.random(6);
	}
}
